package com.itany.boot.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.boot.constant.DictConstant;
import com.itany.boot.constant.StatusConstant;
import com.itany.boot.dao.CourseMapper;
import com.itany.boot.entity.Course;
import com.itany.boot.entity.CourseExample;
import com.itany.boot.exception.CourseExistException;
import com.itany.boot.exception.FileUploadErrorException;
import com.itany.boot.exception.RequestParameterErrorException;
import com.itany.boot.service.CourseService;
import com.itany.boot.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @date 2025/10/12
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private HttpSession session;

    @Override
    public void addCourse(String courseName, String courseInfo, String author, CommonsMultipartFile file, String recommendationGrade, String courseTypeId, HttpSession session) throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {
        if(ParameterUtil.isNull(courseName) || ParameterUtil.isNull(courseInfo) || ParameterUtil.isNull(author) || ParameterUtil.isNull(recommendationGrade) || file.isEmpty() || ParameterUtil.isNull(courseTypeId)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        CourseExample example = new CourseExample();
        example.or()
                .andCourseNameEqualTo(courseName)
                .andCourseTypeIdEqualTo(Integer.parseInt(courseTypeId));
        List<Course> courses = courseMapper.selectByExample(example);
        if(!courses.isEmpty()){
            throw new CourseExistException("课程已经存在");
        }

        Date date = new Date();
        Course course = new Course();
        course.setCourseName(courseName);
        course.setCourseInfo(courseInfo);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade));
        course.setCourseTypeId(Integer.parseInt(courseTypeId));
        course.setCreateDate(date);
        course.setClickNumber(0);
        course.setStatus(DictConstant.COURSE_TYPE_STATUS_ENABLED);

        String path = DictConstant.COURSE_IMAGE_ROOT_FOLDER + new SimpleDateFormat("yyyyMMdd").format(new Date());
        String cp = session.getServletContext().getRealPath(path);
        File f = new File(cp);
        f.mkdirs();

        course.setCoverImageUrl(path + File.separator + file.getOriginalFilename());

        try {
            courseMapper.insertSelective(course);
            file.transferTo(new File(cp,file.getOriginalFilename()));
        } catch (IOException e) {
            throw new FileUploadErrorException("上传图片出错");
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public PageInfo<Course> findPage(Course courseParam, String pageNo, String pageSize) {
        if(ParameterUtil.isNull(pageNo)){
            pageNo = DictConstant.COURSE_DEFAULT_PAGE_NO;
        }
        if(ParameterUtil.isNull(pageSize)){
            pageSize = DictConstant.COURSE_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<Course> courses = courseMapper.selectAll(courseParam);

        for(Course course : courses){
            CourseExample example = new CourseExample();
            example.or()
                    .andIdEqualTo(course.getId());
            List<Course> courses1 = courseMapper.selectByExample(example);
            course.setClickNumber(courses1.size());
        }

        PageInfo<Course> coursePage = new PageInfo<>(courses);
        return coursePage;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Course findById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        return courseMapper.selectByPrimaryKey(Integer.parseInt(id));
    }

    @Override
    public void modifyCourse(String id, String courseName, String courseInfo, String author, CommonsMultipartFile file, String recommendationGrade, String courseTypeId, HttpSession session) throws RequestParameterErrorException, CourseExistException, FileUploadErrorException {
        if(ParameterUtil.isNull(id) || ParameterUtil.isNull(courseName) || ParameterUtil.isNull(courseInfo) || ParameterUtil.isNull(author) || ParameterUtil.isNull(recommendationGrade) ||  ParameterUtil.isNull(courseTypeId)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        CourseExample example = new CourseExample();
        example.or()
                .andCourseNameEqualTo(courseName)
                .andCourseTypeIdEqualTo(Integer.parseInt(courseTypeId))
                .andIdNotEqualTo(Integer.parseInt(id));
        List<Course> types = courseMapper.selectByExample(example);
        if(!types.isEmpty()){
            throw new CourseExistException("该课程已经存在");
        }

        Course course = new Course();
        course.setId(Integer.parseInt(id));
        course.setCourseName(courseName);
        course.setCourseInfo(courseInfo);
        course.setAuthor(author);
        course.setRecommendationGrade(Integer.parseInt(recommendationGrade));
        course.setCourseTypeId(Integer.parseInt(courseTypeId));

        if(file.isEmpty()){
            courseMapper.updateByPrimaryKeySelective(course);
        }else{
            Course c = courseMapper.selectByPrimaryKey(Integer.parseInt(id));
            String cp = session.getServletContext().getRealPath(c.getCoverImageUrl());
            File f = new File(cp);
            f.delete();

            String path = DictConstant.COURSE_IMAGE_ROOT_FOLDER + new SimpleDateFormat("yyyyMMdd").format(new Date());
            cp = session.getServletContext().getRealPath(path);
            File f2 = new File(cp);
            f2.mkdirs();

            course.setCoverImageUrl(path + File.separator + file.getOriginalFilename());

            try {
                courseMapper.updateByPrimaryKeySelective(course);
                file.transferTo(new File(cp,file.getOriginalFilename()));
            } catch (IOException e) {
                throw new FileUploadErrorException("上传课程图片失败");
            }
        }
    }

    @Override
    public void modifyStatus(String id, String status) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id) || ParameterUtil.isNull(status)){
            throw new RequestParameterErrorException("请求参数错误");
        }
        Course type = new Course();
        type.setId(Integer.parseInt(id));
        type.setStatus(Integer.parseInt(status));
        if(type.getStatus() == DictConstant.COURSE_TYPE_STATUS_ENABLED){
            type.setStatus(DictConstant.COURSE_TYPE_STATUS_DISABLED);
        }else{
            type.setStatus(DictConstant.COURSE_TYPE_STATUS_ENABLED);
        }
        courseMapper.updateByPrimaryKeySelective(type);
    }
}
